<template>
    <div>
        <el-popover placement="bottom-start" v-model="visible" :width="realWidth"  trigger="click">
            <el-input
                slot="reference"
                :style="{width:width}"
                v-model="label"
                ref="input"
                :label="labelDate"
                @change="changeInput"
                :id="id" style="width:100%"
            ></el-input>
            <!-- readonly -->
            <div>
                <el-tree
                    class="select-tree"
                    :props="getDefaultProps"
                    :expand-on-click-node="false"
                    @node-click="handleNodeClick"
                    :data="nodes"
                    :style="{height:height+'px'}"
                    @node-expand="handleNodeExpand"
                ></el-tree>
            </div>
        </el-popover>
    </div>
</template>
<script>
import { queryDic } from "common/src/api/dictionary";
export default {
    name: "SelectTree2",
    props: {
        width: {
            default: "100%",
            type: String
        },
        height: {
            default: "160",
            type: String
        },
        data: {
            default: null,
            type: []
        },
        value: {
            default: null
        },
        dataValue: {
            default: "id",
            type: String
        },
        labelDate: {
            // default: "label",
            type: String
        },
        dataLabel: {
            default: "label",
            type: String
        },
        dataParentId: {
            default: "pid",
            type: String
        },
        splitChar: {
            default: "",
            type: String
        }
    },
    data() {
        return {
            id: null,
            label: null,
            visible: false,
            realWidth: this.width,
            getDefaultProps: {
                children: "children",
                label: "label"
            },
            options: {
                nativelist: [] //籍贯
            },
            nodes: [],
            dataList: [],
            expressionList: [],
            expressionDate: [],
        };
    },
    created() {
        this.id = "select-tree-" + Math.floor(Math.random() * 100000);
    },
    mounted() {
        this.qurc();
        this.label = this.labelDate;
        //element-ui的Tree组件，懒加载时设置leaf=true无效，依然显示折叠图标
        //默认加载一级节点，点击时再展开
        // this.nodes = this.getNodesByExpression(
        //     node => node[this.dataParentId] === 0
        // );
    },
    watch: {
        labelDate: {
            handler: function(value) {
                if (value) {
                    this.label = value;
                }
                
            }
        },
        label: {
            handler: function(value) {
                if (value) {
                    this.nodes = [];
                    this.expressionList.forEach(el => {
                        if (el.label.indexOf(value) == 0) {
                            this.nodes.push({
                                label: el.label,
                                id: el.id,
                                pid: el.pid,
                                children: el.children
                            });
                        } else {
                            el.children.forEach(eld => {
                                if (eld.label.indexOf(value) == 0) {
                                    this.nodes.push({
                                        label: el.label + eld.label
                                        // id: el.id,
                                        // pid: el.pid,
                                        // children: el.children
                                    });
                                }
                            });
                        }
                    });
                } else if (value === '') {
                    this.nodes = this.expressionList;
                }
            }
        }

    },
    methods: {
        cancelDialog() {
            this.label = '';
        },
        changeInput(val) {
            this.$emit("change", val, this.dataList);
        },
         qurc() {
            const data = {
                lang: this.$store.getters.language || "cn",
                type: "allChild",
                keys: [
                    "G_XZQY"   //籍贯 出生地
                ]
            };
            queryDic(data).then(res => {
                if (res.code === 200) {
                 this.fillSelectlist(res.data);
                }
            });
        },
         fillSelectlist(data) {
           this._fill("nativelist", data.G_XZQY);
        },
        _fill(type, data) {
            for (const key in data) {
                this.options[type].push({
                    value: key,
                    label: data[key]
                });
            }
            // this.data = this.getCitys(data);
            this.data = this.getCitys(this.options.nativelist);
            let v = this.data.find(v => v[this.dataValue] == this.value);
            if (v) {
                this.label = this.getNodeLabel(v);
            }
            let input = document.getElementById(this.id);
            if (input && input.offsetWidth) {
                this.realWidth = input.offsetWidth;
            }
            // this.nodes = this.getNodesByExpression(
            //   node => node[this.dataParentId] === 0
            // );
            this.getNodesByExpression(this.data);
        },
        getCitys(options) {
            // console.log(options, 'options');
            
            return options.filter(
                c => c.value.length === 6
            ).filter(c => c.value.substr(4) == "00").map(c => {
                let pid = null;
                if (c.value.substr(4) !== '00') {
                    pid = c.value.substr(0, 4) + '00';
                } else if (c.value.substr(4) === '00' && c.value.substr(2, 2) !== '00') {
                    pid = c.value.substr(0, 2) + '0000';
                } else {
                    pid = 0;
                }
                return {
                    id: c.value,
                    label: c.label.replace(/(^\s*)|(\s*$)/g, ''),
                    pid: pid
                };
            });
        },
        getNodesByExpression(data) {
            this.dataList = data;
            data.forEach(ele => {
                if (ele.pid == 0 && ele.label!='其他') {
                    this.expressionList.push({
                        children: [],
                        id: ele.id,
                        label: ele.label,
                        pid: ele.pid
                    });
                } else {
                    this.expressionDate.push({
                        id: ele.id,
                        label: ele.label,
                        pid: ele.pid
                    });
                }
            });
            if (this.expressionDate) {
                this.expressionList.forEach(elt => {
                    this.expressionDate.forEach(eld => {
                        if (elt.id === eld.pid) {
                            // console.log(ele.pid, 'el', eld.id);
                            this.expressionList.forEach(eltd => {
                                elt.children.push({
                                    id: eld.id,
                                    label: eld.label,
                                    pid: eld.pid
                                });
                            });
                            
                        }
                    });
                });
            }
            let obj = {};
            // let peon = [];
            this.expressionList.forEach(el => {
                el.children = el.children.reduce((cur,next) => {
                    obj[next.id] ? "" : obj[next.id] = true && cur.push(next);
                    return cur;
                },[]);
            // console.log(peon, 'this.peon');
            });
            this.nodes = this.expressionList;
            
            // console.log(this.expressionList, 'this.peon');
        },
        // getNodesByExpression(expression) {
        //     return this.data.filter(expression).map(node => {
        //         let isLeaf = !this.data.some(
        //             n =>
        //                 n[this.dataParentId] !== 0 &&
        //                 n[this.dataParentId] == node[this.dataValue]
        //         );
        //         // console.log(node, 'node');
                
        //         let obj = {
        //             label: node[this.dataLabel],
        //             // children: node[this.dataValue]
        //             children: isLeaf ? undefined : [{ placeholder: true }]
        //         };
        //         obj[this.dataValue] = node[this.dataValue];
        //         obj[this.dataParentId] = node[this.dataParentId];
        //         return obj;
        //     });
        // },
        handleNodeClick(item) {
            this.label = this.getNodeLabel(item);
            this.$emit("input", this.label);
            this.visible = false;
        },
        getNodeLabel(item) {
            if (item[this.dataParentId]) {
                let parent = this.data.find(
                    c => c[this.dataValue] == item[this.dataParentId]
                );
                if (parent) {
                    if (parent[this.dataParentId]) {
                        let grandfather = this.data.find(
                            c => c[this.dataValue] == parent[this.dataParentId]
                        );
                        if (grandfather) {
                            return (
                                grandfather[this.dataLabel] +
                                this.splitChar +
                                parent[this.dataLabel] +
                                this.splitChar +
                                item[this.dataLabel]
                            );
                        }
                    } else {
                        return (
                            parent[this.dataLabel] +
                            this.splitChar +
                            item[this.dataLabel]
                        );
                    }
                }
            }
            return item[this.dataLabel];
        },
        handleNodeExpand(obj, node, vueComponent) {
            if (obj.children && obj.children.length === 1 && obj.children[0].placeholder) {
                obj.children = this.getNodesByExpression(
                    v =>v[this.dataParentId] !== 0 && v[this.dataParentId] == obj[this.dataValue]
                );
            }
        }
    }
};
</script>
<style lang="scss" scoped>
.select-tree {
    width: 90%;
    overflow: auto;
}
</style>